package com.snow.blog.service.impl;

import com.snow.blog.repository.TagRepository;
import com.snow.blog.repository.entity.Tag;
import com.snow.blog.service.ITagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @create by SNOW 2018.07.18
 */
@Service
@Slf4j
public class TagService implements ITagService {

    @Autowired
    private TagRepository tagRepository;

    @Override
    public List<Tag> getAllTag(String targetUserId, String currentUserId) {
        if (StringUtils.isEmpty(targetUserId)) {
            return tagRepository.findAllByEnabledIsTrue();
        }
        return tagRepository.findTagsByUserId(targetUserId);
    }

    @Override
    public Tag saveTag(Tag tag, String userId) {
        tag.setUserId(userId);
        tag.setEnabled(true);
        return tagRepository.save(tag);
    }

    @Override
    public List<Tag> saveTag(List<Tag> tags, String userId) {
        if (!CollectionUtils.isEmpty(tags)) {
            tags.forEach(tag -> {
                tag.setUserId(userId);
                tag.setEnabled(true);
            });
            List<Tag> oldTags = tagRepository.findAllByUserIdAndNameIsIn(userId, tags.stream().map(Tag::getName).collect(Collectors.toList()));
            Map<String, Tag> oldTagMap = new HashMap<>();
            Map<String, Tag> newTagMap = new HashMap<>();
            if (null == oldTags) {
                oldTags = new ArrayList<>();
            } else {
                oldTags.forEach(tag -> oldTagMap.put(tag.getName(), tag));
            }
            tags.forEach(tag -> {
                if (!oldTagMap.containsKey(tag.getName())) {
                    newTagMap.put(tag.getName(), tag);
                }
            });
            List<Tag> newTags = new ArrayList<>(newTagMap.values());
            if (newTags.size() > 0) {
                List<Tag> newTagsSaved = tagRepository.save(newTags);
                oldTags.addAll(newTagsSaved);
            }
            return oldTags;
        }
        return tags;
    }
}
